#include "streamrecorderwithfailover.h"
#include "streamrecorder.h"
#include "streamrecordercontroller.h"

StreamRecorderWithFailover::StreamRecorderWithFailover(const StreamRecorderConfig& config,
                                                       const QStringList& urls, QObject* parent)
    : QObject { parent }, config_(config), urls_(urls)
{
    stream_recorder_ = new StreamRecorderController(0, this);
    connect(stream_recorder_, &StreamRecorderController::positionChanged, this,
            &StreamRecorderWithFailover::positionChanged);
    connect(stream_recorder_, &StreamRecorderController::finished, this,
            &StreamRecorderWithFailover::finished);
    connect(stream_recorder_, &StreamRecorderController::errorOccurred, this,
            &StreamRecorderWithFailover::onError);
    stream_recorder_->start(config);
}

StreamRecorderWithFailover::~StreamRecorderWithFailover()
{
    disconnect(stream_recorder_, nullptr, this, nullptr);
    delete stream_recorder_;
}

bool StreamRecorderWithFailover::isRunning() const
{
    return stream_recorder_->isRunning();
}

void StreamRecorderWithFailover::start()
{
    if (!urls_.empty()) {
        index_ = 0;
        for (int i = 0; i < urls_.size(); ++i) {
            if (!urls_.at(i).isEmpty()) {
                index_ = i;
                config_.inputUrl = urls_.at(i);
                stream_recorder_->start(config_);
                return;
            }
        }
    }
    Q_EMIT errorOccurred(StreamRecorder::INVALID_STREAM_URL_ERROR, tr("No invalid stream url."));
}

void StreamRecorderWithFailover::stop()
{
    stream_recorder_->stop();
}

void StreamRecorderWithFailover::terminate()
{
    stream_recorder_->terminate();
}

void StreamRecorderWithFailover::onError(int error, const QString& message)
{
    if ((error == StreamRecorder::INVALID_STREAM_URL_ERROR
         || error == StreamRecorder::CANT_ACCESS_STREAM_SOURCE_ERROR)
        && ++index_ < urls_.size()) {
        config_.inputUrl = urls_.at(index_);
        stream_recorder_->start(config_);
    } else {
        Q_EMIT errorOccurred(error, message);
    }
}
